export default class ImageLoad {
  constructor(options = {}) {
    const DEFAULT = {
      callback(type, res) {
        console.log('载图片完成回调', type, res);
      },
      isRelease: true, // 释放图片对象
      timeout: 8000, // 预加载图片的超时时间
      isRetry: false, // 是否自动重试
      maxRetry: 3 // 最大重试次数
    };
    this.options = Object.assign(DEFAULT, options)
    this._timer;
    this.status = 'init';
    this.count = 0; // 图片加载次数
    this.width = 0;
    this.height = 0;
    this.img = new Image();
  }

  /**
   * @function imageLoad 请求图片
   * @param {object} image 图片数据
   * @return 无
   */
  load(src, options) {
    this.options = Object.assign(this.options, options)
    const { isRelease, timeout, callback } = this.options;
    this._startTime = Date.now();
    this.status = 'loading';
    this.count += 1;
    this.src = src;

    callback(this);
    this.img.onload = () => {
      this.width = this.img.width;
      this.height = this.img.height;
      this.status = 'loaded';
      if (isRelease) this.img = null;
      this.finish();
    };
    this.img.onerror = (e) => {
      this.status = 'error';
      console.log(e)
      this.finish();
    };
    // 超时
    this._timer = setTimeout(() => {
      this.img.src = ''; // 取消请求
      this.status = 'timeout';
      this.finish();
    }, timeout);
    this.img.src = src
  }

  finish() {
    this._timer && clearTimeout(this._timer);
    this.time = Date.now() - this._startTime; // 加载时间
    const { isRetry, maxRetry, callback } = this.options;
    if (isRetry && this.count <= maxRetry && ['error', 'timeout'].indexOf(this.status) > -1) {
      this.load(this.src, callback);
    } else {
      callback(this);
    }
  }
}
